package com.xxx.system.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.xxx.system.jwt.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception {
        if("front".equals(request.getHeader("requestType"))){
            return true;
        }
        String token=request.getHeader("token");

        if (StrUtil.isBlank(token)){
            response.setContentType(ContentType.JSON.toString());
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");

            return false;
        }

        try {
            JwtUtil.parseJwtToken(token);
        } catch(Exception e) {
            e.printStackTrace();

            response.setContentType(ContentType.JSON.toString());
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");

            return false;
        }

        return true;
    }
}